package com.ebt.m.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CallLog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.ui.ActivityCustomerNote;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.commons.model.http.APIsFactory;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.data.rxModel.apibean.PhoneEventAddParam;
import com.ebt.m.commons.utils.PrefKit;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.NetUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by andy.wang on 2016/12/16.
 */

public class PhoneStateReceiver extends BroadcastReceiver {

    private static boolean isOutGoingCall = false;
    private static boolean isOffHook = false;
    public static final String CALLING_FLAG = "calling_flag";
    public static final String CALLING_INFO = "calling_info";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            String customerId = PrefKit.getString(context, CALLING_FLAG);
            if (!TextUtils.isEmpty(customerId)) {
                isOutGoingCall = true;
                PrefKit.writeString(context, CALLING_INFO, customerId + "=" + System.currentTimeMillis());
                PrefKit.writeString(context, CALLING_FLAG, "");
            }
        } else if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Service.TELEPHONY_SERVICE);
            if (tm.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)
                isOffHook = true;
            if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
                if (isOutGoingCall == true && isOffHook == true) {
                    isOffHook = false;
                    isOutGoingCall = false;
                    String phoneNumber = intent.getStringExtra("incoming_number");
                    EBTAPI userApi = AppInitService.getEbtApi();
                    String callInfo = PrefKit.getString(AppContext.getInstance(), CALLING_INFO);
                    if (!TextUtils.isEmpty(callInfo)) {
                        String[] infos = callInfo.split("=");
                        PrefKit.writeString(AppContext.getInstance(), CALLING_INFO, "");
                        String customerId = infos[0];
                        if (!TextUtils.isEmpty(customerId)) {
                            if (!NetUtils.isNetworkAvailable(AppContext.getInstance())) {
                                ToastUtil.showToast(AppContext.getInstance().getString(R.string.network_fail));
                                return;
                            }
                            Intent i = new Intent(AppContext.getInstance(), ActivityCustomerNote.class);
                            i.putExtra(CustomerConstant.CUSTOMER_UUID, customerId);
                            i.putExtra(CustomerConstant.CustomerNote.MODE, CustomerConstant.CustomerNote.MODE_ADD);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            AppContext.getInstance().startActivity(i);
                        }
                        Observable.just(infos)
                                .delay(1500, TimeUnit.MILLISECONDS)
                                .map(arrays -> createPhoneParam(arrays, phoneNumber))
                                .flatMap(phoneParam -> userApi.createPhoneEvent(infos[0], phoneParam))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(resultBean -> {
                                    try {
                                        Logger.i(resultBean.body().string());
                                    } catch (Exception e) {
                                        Logger.e(e);
                                    }
                                }, throwable -> {
                                    throwable.printStackTrace();
                                });
                    }
                }
            }
        }
    }

    private PhoneEventAddParam createPhoneParam(String[] infos, String phoneNumber) {
        PhoneEventAddParam addParam = new PhoneEventAddParam();
        addParam.phoneNo = phoneNumber;
        ContentResolver cr = AppContext.getInstance().getContentResolver();
        long talkTime = Long.valueOf(infos[1]);
        long talkTimeBegin = talkTime - 2000;
        long talkTimeEnd = talkTime + 2000;
        String selection = " ( " + CallLog.Calls.DATE + " BETWEEN " + talkTimeBegin + " AND " + talkTimeEnd + ") AND " + CallLog.Calls.TYPE + " =  " + CallLog.Calls.OUTGOING_TYPE + " AND " + CallLog.Calls.DURATION + " >0 ";
        Cursor cs;
        cs = cr.query(CallLog.Calls.CONTENT_URI,
                new String[]{
                        CallLog.Calls.CACHED_NAME,
                        CallLog.Calls.NUMBER,
                        CallLog.Calls.TYPE,
                        CallLog.Calls.DATE,
                        CallLog.Calls.DURATION
                }, selection, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        if (cs != null && cs.getCount() > 0) {
            cs.moveToFirst();
            String callNumber = cs.getString(1);
            if (!callNumber.equals(phoneNumber))
                addParam.phoneNo = callNumber;
            addParam.talkTime = DateUtils.parseSecondToFriendlyText(cs.getString(4));
        }

        return addParam;
    }

}
